package com.project.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.mapper.UserMapper;

import com.project.pojo.User;
import com.project.service.UserService;
import com.project.utils.JwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean RegisterByPassword(User user) {
        String salt= BCrypt.gensalt();
        String slatPassword= BCrypt.hashpw(user.getPassword(),salt);
        user.setPassword(slatPassword);
        System.out.println("slatPassword"+slatPassword);
        if (userMapper.insert(user)>0){
            return true;
        };
        return false;
    }

    @Override
    public User loginByPassword(User user) {
      QueryWrapper<User> queryWrapper=new QueryWrapper();
//        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("phone",user.getPhone());
        User isUser=userMapper.selectOne(queryWrapper);
        if (Objects.isNull(isUser)){

            return null;
        }
        if (BCrypt.checkpw(user.getPassword(),isUser.getPassword())){

            redisTemplate.opsForValue().set("user", JSON.toJSON(isUser),JwtUtil.JWT_TTL);
            
            return isUser;
        }



        return null;
    }
}
